import net.sf.mpxj.reader.ProjectReaderUtility
import net.sf.mpxj.Task
import scala.collection.JavaConversions._
import java.text.SimpleDateFormat
import java.text.DecimalFormat
import com.mongodb.casbah.Imports._
import com.mongodb.casbah.commons.conversions.scala._
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.nio.file.FileSystems
import java.nio.file.Paths
import java.nio.file.Files
import scala.collection.JavaConversions._
import org.joda.time.DateTime
import scala.collection.mutable.ArrayBuffer

class PrjPlan(prjFile: String) {

  val prjReader = ProjectReaderUtility.getProjectReader(prjFile)
  val mpx = prjReader.read(prjFile)
  val resourcePattern = """resource=([\w|\s]+)\sstart""".r
  val df = new SimpleDateFormat("yyyy-MM-dd")
  val decf = new DecimalFormat("#.# d");

  RegisterJodaTimeConversionHelpers()
  val mongoCollection = MongoClient()("prjplan")("plan")
  val fileInfoCollection = MongoClient()("prjplan")("file")

  def cleanData = {
    mongoCollection.remove(MongoDBObject.empty)
    fileInfoCollection.remove(MongoDBObject.empty)
  }

  /*Get MS Project Plan file info*/
  def fileInfo = {
    val fileInfo = MongoDBObject("lastSaved" -> df.format(mpx.getProjectHeader().getLastSaved()))
    fileInfoCollection += fileInfo
  }

  /* contribution */
  def effortsOnRelease = {
    
      val cn_devs = ArrayBuffer("Tony Zhang",
    "Lei Zhang",
    "Yolanda Liu",
    "Ben An",
    "Terry Wang",
    "Wayne Wang",
    "Adward Tu",
    "Frank Li",
    "Gordon Cheng",
    "Morphy Tong",
    "Gary Chen",
    "Lucien Wang")
	  
    var total=0.0
    var cn_total=0.0
    var non_cn_total=0.0
    val releaseMonogoObject = MongoDBObject("OutlineNum" -> "^1.5.2.*".r)
    for (rawtask <- mongoCollection.find(releaseMonogoObject).toList) {
      val outlineNum = rawtask.as[String]("OutlineNum")
      val taskName = rawtask.as[String]("Name")
      val resourceName = rawtask.as[String]("ResourceName")
      val work = rawtask.as[Double]("Work")
      
      if (!resourceName.trim().equals("") && !resourceName.trim().equals("Unassigned")){
    	  //total
    	  total= total + work
    	  
    	  println(resourceName,cn_devs.contains(resourceName))
    	  if (cn_devs.contains(resourceName)){
    	    cn_total=cn_total+ work
    	  }else{
    	    non_cn_total=non_cn_total+work
    	  }
      }
    }
      println(total,cn_total,non_cn_total)
  }

  def prjData =
    for (task <- mpx.getAllTasks.toList) {
      if (task.getName != null) {
        val taskItem = MongoDBObject(
          "UniqueID" -> task.getUniqueID,
          "Name" -> task.getName,
          "OutlineNum" -> task.getOutlineNumber,
          "ResourceName" -> resourceName(task).trim(),
          "StartDate" -> new DateTime(task.getStart),
          "FinishDate" -> new DateTime(task.getFinish),
          "Duration" -> duration(task),
          "PercntComplete" -> task.getPercentageComplete,
          "Work" -> task.getWork().getDuration())

        mongoCollection += taskItem
      }
      val outlineNum = MongoDBObject("OutlineNum" -> 1)
      mongoCollection.createIndex(outlineNum)
    }

  def resourceName(task: Task): String = {
    for (resourcePattern(name) <- resourcePattern.findAllIn(task.getResourceAssignments.toString)) return name
    return ""
  }

  def duration(task: Task): String = {
    val dur = task.getDuration()
    if (dur != null) decf.format(dur.getDuration()) else ""
  }
}

object PrjPlan extends App {

  def prjPlanFile: String = {
    val path: Path = Paths.get(System.getProperty("user.dir"))
    val directoryStream = Files.newDirectoryStream(path, "*.mpp")
    for (file <- directoryStream.toList) { return file.toString() }

    return ""
  }

  val x = new PrjPlan(prjPlanFile)
  println(x.cleanData)
  println(x.fileInfo)
  println(x.prjData)
  println(x.effortsOnRelease)
}